package com.dongluhitec.card.deviceUpdeter.util;

import java.awt.Component;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;

import com.dongluhitec.card.deviceUpdeter.Model;
import com.dongluhitec.card.deviceUpdeter.bean.Device;
import org.apache.commons.net.tftp.TFTP;
import org.apache.commons.net.tftp.TFTPClient;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UploadFiles {
	private Logger LOGGER = LoggerFactory.getLogger(UploadFiles.class);
	private String path;
	private Component chatFrame;
	private Model model;
	
	
	public UploadFiles(Model model){
		this.model = model;
	}
	
	public String choice() {
		this.model.setLabel("正在选择文件......");
		int result = 0;
		JFileChooser fileChooser = new JFileChooser();
 
		this.model.setLabel("");
		
		FileSystemView fsv = FileSystemView.getFileSystemView();

		LOGGER.debug("桌面路劲{}", fsv.getHomeDirectory());

		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());

		fileChooser.setDialogTitle("请选择要上传的文件");

		fileChooser.setApproveButtonText("确定");

		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

		result = fileChooser.showOpenDialog(chatFrame);

		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			LOGGER.debug("文件路径{}", path);
		}
		return path;
	}

	// 上传
	boolean receiveFile = true, closed;
	int transferMode = TFTP.BINARY_MODE, argc;
	String arg, hostname, localFilename, remoteFilename;
	TFTPClient tftp;
	int a=0;

	public void upload(List<Device> selectedList, ProgressBar progressBar) {
		new Thread(){
			public void run(){
				for (int i = 0; i < selectedList.size(); i++) {
					labelPrompt1();
					Device device = new Device();
					try {
						DeviceUtil IAPBody=new DeviceUtil();
						System.out.println("selectedList.get(i).getTyIp()===="+selectedList.get(i).getTyIp());
						IAPBody.enterIAP(selectedList.get(i).getTyIp());
						Thread.sleep(3000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					} 
					if (selectedList.isEmpty()) {
						return;
					}
					if (path == null || path.isEmpty()) {
						return;
					}
					if (selectedList != null) {
						device = selectedList.get(i);
					}
					
					LOGGER.debug("上传IP{}", device.getTyIp());
					localFilename = path;
					
					remoteFilename = path.substring(path.lastIndexOf("\\") + 1, path.length());
  
					tftp = new TFTPClient();
					
					tftp.setDefaultTimeout(10000);
					try {
						tftp.open();
					} catch (SocketException e) {
						e.printStackTrace();
						e.printStackTrace();
						System.err.println("Error: could not open local UDP socket.");
						System.err.println(e.getMessage());
						System.exit(1);
					}

					closed = false;

					if (receiveFile) {

						FileInputStream input = null;
						try {
							input = new FileInputStream(localFilename);
						} catch (IOException e) {
							tftp.close();
							System.err.println("Error: could not open local file for reading.");
							System.err.println(e.getMessage());
							System.exit(1);
						}
						try {
							LOGGER.debug("正在上传，请稍候：{}");
							long start_get_ip = System.currentTimeMillis();
							tftp.sendFile(remoteFilename, transferMode, input, selectedList.get(i).getTyIp(), 10001);
							a= a+1;
							if(System.currentTimeMillis()-start_get_ip==30000){
								LOGGER.debug("上传超时{}");
								continue;
							}
							Display.getDefault().syncExec(new Runnable() {
							    public void run() {
							    	progressBar.setMaximum(selectedList.size());
									progressBar.setSelection(a);
									labelPrompt();
							}
							    });
							selectedList.get(i).setStatus(true);
							LOGGER.debug("上传所需时间{}",System.currentTimeMillis()-start_get_ip);
							LOGGER.debug("上传成功{}");
							
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							try {
								if (input != null) {
									input.close();
								}
								closed = true;
							} catch (IOException e2) {
								closed = false;
								System.err.println("Error: error closing file.");
								System.err.println(e2.getMessage());
							}
							if (!closed) {
								System.exit(1);
							}
						}
					}
				}
			}
		}.start();
	}
	
	
	
	public void labelPrompt(){
		this.model.setLabel("上传成功......");
	}
	
	public void labelPrompt1(){
		this.model.setLabel("正在上传......");
	}
}
